package com.demo.security.handle;


import cn.hutool.json.JSONUtil;
import com.demo.security.model.ConstantKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 未登录或者token失效访问接口时，自定义的返回结果
 * @Auther: zhaoxinguo
 * @Date: 2018/9/20 14:55
 * @Description: 自定义认证拦截器
 */
public class Http401AuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final String headerValue;

    private static final Logger logger = LoggerFactory.getLogger(Http401AuthenticationEntryPoint.class);

    public Http401AuthenticationEntryPoint(String headerValue) {
        this.headerValue = headerValue;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        logger.info("请求url:{}",request.getRequestURL());
        response.setHeader(ConstantKey.HEADER_KEY, this.headerValue);
//        Map<String, Object> map = new HashMap<>();
//        map.put("msg", "未登录");
//        response.getWriter().println(JSONUtil.parse(map));
//        response.getWriter().flush();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
    }

}